package com.papper.mng.controller.system;

import com.google.common.collect.Sets;
import com.papper.common.bean.sys.SysResource;
import com.papper.common.bean.sys.SysSystem;
import com.papper.common.enums.DataStatusEnum;
import com.papper.common.exception.ServiceException;
import com.papper.common.service.sys.SysResourceService;
import com.papper.common.service.sys.SysSystemService;
import com.papper.common.utils.tool.StringTool;
import com.papper.mng.controller.BaseAction;
import com.papper.mng.domain.DwzResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

/**
 * The type Request mapping action.
 *
 * @Author:Lajiao
 * @Date:2014年8月21日
 * @Time:下午12:42:13
 * @Description:系统请求地址列表
 */
@Controller
@RequestMapping("/request/mapping")
public class RequestMappingAction extends BaseAction {
    @Resource
    SysResourceService sysResourceService;
    @Resource
    SysSystemService   sysSystemService;

    /**
     * Index string.
     *
     * @param _request the request
     * @param model    the model
     * @return the string
     */
    @RequestMapping(value = "")
    public String index(HttpServletRequest _request, Model model) {
        SysSystem       sysSystem = sysSystemService.findSysSystem();
        TreeSet<String> reqList   = Sets.newTreeSet();
        Example         example   = new Example(SysResource.class);
        example.createCriteria().andEqualTo("systemId", sysSystem.getId());
        List<SysResource> sysResourceList = sysResourceService.find(example);
        // 获取请求地址一览
        WebApplicationContext                  wac  = (WebApplicationContext) _request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        RequestMappingHandlerMapping           rmhp = wac.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map  = rmhp.getHandlerMethods();
        for (Iterator<RequestMappingInfo> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
            RequestMappingInfo info = iterator.next();
            if (info == null) {
                continue;
            }
            if (info.getPatternsCondition() == null) {
                continue;
            }
            if (info.getPatternsCondition().getPatterns() == null) {
                continue;
            }
            if (info.getPatternsCondition().getPatterns().size() <= 0) {
                continue;
            }
            String compUrl = StringTool.nullToEmpty(info.getPatternsCondition().getPatterns().toArray()[0]);
            if (StringUtil.isEmpty(compUrl)) {
                continue;
            }
            compUrl = compUrl.substring(1);
            SysResource sysResource = null;
            if (sysResourceList != null) {
                for (SysResource sysResource1 : sysResourceList) {
                    if (sysResource1.getResUrl().equalsIgnoreCase(compUrl)) {
                        sysResource = sysResource1;
                        break;
                    }
                }
            }
            if (sysResource == null && !compUrl.startsWith("sys") && !compUrl.startsWith("test")) {
                reqList.add(compUrl);
            }
        }
        model.addAttribute("reqList", reqList);
        model.addAttribute("reqListSize", reqList.size());
        return render("system/request/mapping");
    }

    /**
     * 系统字典_新增
     *
     * @param model the model
     * @param url   the url
     * @return the string
     * @throws IOException the io exception
     */
    @GetMapping(value = "/add")
    public String add_get(Model model, String url) {
        model.addAttribute("url", url);
        model.addAttribute("resUrl", url + "");
        model.addAttribute("resLimit", StringTool.getCamelCaseString(url, true));
        return render("system/request/mappingAdd");
    }

    /**
     * Add post dwz response.
     *
     * @param _request the request
     * @return the dwz response
     * @throws IOException the io exception
     */
    @PostMapping(value = "/add")
    @ResponseBody
    public DwzResponse add_post(HttpServletRequest _request) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }

        Integer upId     = StringTool.parseInteger(_request.getParameter("upId"), null);
        String  resUrl   = _request.getParameter("resUrl");
        String  resLimit = _request.getParameter("resLimit");
        Integer resType  = StringTool.parseInteger(_request.getParameter("resType"), null);
        String  resName  = _request.getParameter("resName");
        Integer resSort  = StringTool.parseInteger(_request.getParameter("resSort"), null);

        if (StringUtil.isEmpty(resUrl) || StringUtil.isEmpty(resLimit) || resType == null || StringUtil.isEmpty(resName) || resSort == null) {
            return new DwzResponse("300", "必传参数为空");
        }

        SysResource upResource = sysResourceService.findById(upId);
        if (upResource == null) {
            return new DwzResponse("300", "父资源不存在");
        }

        SysResource add = new SysResource();
        add.setSystemId(upResource.getSystemId());
        add.setModelId(upResource.getModelId());
        add.setResType(resType);
        add.setResName(resName);
        add.setResUrl(resUrl);
        add.setResLimit(resLimit);
        add.setResSort(resSort);
        add.setUpId(upId);
        add.setUpFamily("");
        add.setUpChild(0);
        add.setDataStatus(DataStatusEnum.OPEN.getCode());
        add.setCreateTime(new Date());
        add.setModifyTime(new Date());
        sysResourceService.save(add);
        // 维护组树信息
        sysResourceService.matchFamily(add);
        sysResourceService.matchChild(sysResourceService.findById(add.getUpId()));
        return new DwzResponse("200", "系统资源添加成功!!!");
    }
}
